import { ComponentProps, Computed, Mut, VueComponent } from "vue3-oop"
import { FormItem, Upload, Button, UploadChangeParam,message, UploadFile } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue'
import { WidgetNode } from '../../types'
import { UPLOAD } from "./attr-upload";

interface IProps {
  widgetNode: WidgetNode
}
export default class FvrUpload extends VueComponent<IProps> {
  static defaultProps: ComponentProps<IProps> = {
    widgetNode: {}
  }

  constructor(
  ) {
    super();
  }

  @Mut() state = {
    loading: false,
    fileMap: new Map<string,UploadFile<any>>(),
  }

  @Computed() get fileList(){
    return this.state.fileMap.forEach(()=>{

    })
  }

  beforeUpload = (file: any) => {
    // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    // if (!isJpgOrPng) {
    //   message.error('You can only upload JPG file!');
    // }
    // const isLt2M = file.size / 1024 / 1024 < 2;
    // if (!isLt2M) {
    //   message.error('Image must smaller than 2MB!');
    // }
    // return isJpgOrPng && isLt2M;
    return true;
  };

  handleChange = (info: UploadChangeParam) => {
    const { widgetNode } = this.props;
    const { widgetItem } = widgetNode;
    const attr = widgetItem[widgetItem.type] as UPLOAD;
    // 不在state中则加入state的fileList
    if(!this.state.fileMap.has(info.file.uid)){
      this.state.fileMap.set(info.file.uid,info.file);
    }
    const stateFile = this.state.fileMap.get(info.file.uid) as UploadFile<any>;
    if(info.file.status==='uploading'){
      stateFile.percent = info.file.percent;
    }else if(info.file.status==='done'){
      stateFile.status = 'done';
      stateFile.url = info.file.response.url;
    }else if(info.file.status==='error'){
      stateFile.status = 'error';
      message.error('上传失败');
    }

  };

  render() {
    const { widgetNode } = this.props;
    const { widgetItem } = widgetNode;
    const attr = widgetItem[widgetItem.type] as UPLOAD;

    const labelAlign = attr.formitem_labelAlign;
    const labelCol = { style: { width: `${attr.formitem_labelWidth}px` } }
    const isRequired = attr.layout_status==='4'

    const rules = [];
    if(isRequired){
      rules.push({ required: true, message: `请选择[${attr.field_label}]` })
    }

    return (
      <FormItem
        name={attr.field_code} 
        labelCol={labelCol} 
        labelAlign={labelAlign} 
        label={attr.field_label} 
        rules={rules}
      >
        <Upload 
          action={"https://www.mocky.io/v2/5cc8019d300000980a055e76"}
          multiple={true}
          fileList={[...this.state.fileMap].map((item)=>item[1])}
          beforeUpload={this.beforeUpload}
          onChange={this.handleChange}
        ><Button size="small"><UploadOutlined/>点击上传</Button></Upload>
      </FormItem>
    )
  }
}